// pages/home/home.js
let filter = require("../../utils/filter.js")
let api = require("../../api/api.js")

Page(
  {
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    userCourseList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    filter.identityFilter() //判断是否登录
    this.setData({ userInfo: wx.getStorageSync('userInfo') })
    this.getUserCourse();
    this.getUserFav()
  },

  onShow: function(){
    
  },

  getUserCourse:function(){
    let that = this;
    api.userCourse().then(res=>{
      console.log(res)
      let orderData = res.data
      let userCourseList = []
      for(var i = 0; i < orderData.length; i ++){
        if(orderData[i].course.length != 0 && (orderData[i].pay_status == "TRADE_SUCCESS" || orderData[i].pay_status == "TRADE_FINISHED")){
          for(var j = 0; j < orderData[i].course.length; j++){
            userCourseList.push(orderData[i].course[j])
          }
        }
      }
      that.setData({ userCourseList: userCourseList })
      console.log(that.data.userCourseList)
    })
  },

  getUserFav:function(){
    api.userFav().then(res=>{
      console.log(res)
      let userFavList = []
      for(let i = 0; i < res.data.length; i++){
        userFavList.push(res.data[i].course)
      }

      wx.setStorageSync('userFav', userFavList)
    })
  },

  toOrder: function(e) {
    const type = Number(e.currentTarget.dataset.type)
    wx.navigateTo({
      url: '/pages/userOrder/userOrder',
    })
  },

  toDetail:function(e){
    let courseId = e.target.dataset.index
    console.log(courseId)
    wx.navigateTo({
      url: '/pages/courseDetial/courseDetial?course_id='+ courseId,
    })
  },

  goShopping:function(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  goCart:function(){
    wx.navigateTo({
      url: '/pages/shoppingCart/shoppingCart',
    })
  },

  goCollection:function(){
    wx.navigateTo({
      url: '/pages/collection/collection',
    })
  }
  
})